package cn.tedu.boot21.controller;

import cn.tedu.boot21.entity.User;
import cn.tedu.boot21.utils.DBUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Response;
import java.io.PipedWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Controller
public class UserController {
    @RequestMapping("/reg")
    @ResponseBody
    public String reg(User user, HttpServletResponse response){
        try(Connection conn = DBUtils.getConn()){
            response.setContentType("text/html;charset=utf-8");
            String sql1 = "select id from user where username=?";
            PreparedStatement ps1 = conn.prepareStatement(sql1);
            ps1.setString(1,user.getUsername());
            ResultSet rs = ps1.executeQuery();
            if (rs.next()){
                return "用户名已存在!";
            }

            String sql = "insert into user values(null,?,?,?)";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            ps.setString(3, user.getNick());
            ps.executeUpdate();
            return "注册成功!";
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return user.toString();
    }


    @RequestMapping("/login")
    @ResponseBody
    public String login(User user,HttpServletResponse response) {
        System.out.println("user = " + user);
        response.setContentType("text/html;charset=utf8");
        if (!user.getUsername().isEmpty()) {
            try (Connection conn = DBUtils.getConn()) {
                String sql = "select password from user where username=?";
                PreparedStatement ps = conn.prepareStatement(sql);
                ps.setString(1,user.getUsername());
                ResultSet rs = ps.executeQuery();
                if (rs.next()){
                    if (rs.getString(1).equals(user.getPassword())){
                        return "登陆成功!";
                    }
                        return "密码错误,登陆失败!";
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return "用户名不存在,请您重新输入!";
    }
}
